class AudioPlayer {
  constructor() {
    this.context = ''
    this.onCanPlay = []
    this.onPlay = []
    this.onTimeUpdate = []
    this.onPause = []
    this.onEnded = []
    this.onError = []
  }

  init() {
    this.context = document.createElement('audio')
    const events = ['onCanPlay', 'onPlay', 'onTimeUpdate', 'onPause', 'onEnded', 'onError']

    events.forEach((event) => {
      this.context.addEventListener(event.replace('on', '').toLocaleLowerCase(), (e) => {
        if (!Array.isArray(this[event])) return

        this[event].forEach((fn) => {
          fn(e)
        })
      })
    })
  }

  on(type, fn) {
    if (!type || !fn) return

    const event = this[type]
    if (!event || typeof event != 'object') return

    event.push(fn)
  }
  off(type, fn) {
    if (!type || !fn) return

    const event = this[type]
    if (!event || typeof event != 'object') return

    this[type] = event
      .map((handler) => {
        if (handler === fn) {
          return null
        } else {
          return handler
        }
      })
      .filter((i) => !!i)
  }

  play() {
    if (!this.context) return

    this.context.play()
  }

  pause() {
    if (!this.context) return

    this.context.pause()
  }

  stop() {
    if (!this.context) return

    this.context.pause()
    this.onPause.forEach((fn) => fn())
    this.context.currentTime = 0
  }
}

export default AudioPlayer
